<template>
  <div class="health-profile">
    <div v-if="loading" class="loading">
      <el-loading :loading="loading" text="加载中..."></el-loading>
    </div>

    <div v-else>
      <!-- 居民信息 -->
      <div class="section">
        <h3 class="section-title">居民信息</h3>
        <el-row :gutter="20" class="info-grid">
          <el-col :span="6">
            <div class="info-item">
              <span class="label">居民编号</span>
              <span class="value">{{ residentData.residentNumber || '' }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <span class="label">姓名</span>
              <span class="value">{{ residentData.name || '' }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <span class="label">头像</span>
              <div class="avatar-wrapper">
                <img :src="getAvatarUrl(residentData.avatar)" class="avatar" />
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <span class="label">身份证号</span>
              <span class="value">{{ residentData.idCard || '' }}</span>
            </div>
          </el-col>

          <el-col :span="6">
            <div class="info-item">
              <span class="label">手机号码</span>
              <div class="phone-wrapper">
                <span class="value">{{ residentData.phone || '' }}</span>
                <el-button
                  type="primary"
                  size="small"
                  :icon="ChatDotRound"
                  @click="openSmsDialog"
                  class="sms-btn"
                >
                  发短信
                </el-button>
              </div>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <span class="label">现居地址</span>
              <span class="value">{{ residentData.address || '' }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <span class="label">登录密码</span>
              <span class="value">{{ residentData.password || '' }}</span>
            </div>
          </el-col>

          <el-col :span="6">
            <div class="info-item">
              <span class="label">行政区划</span>
              <span class="value">{{ residentData.district || '' }}</span>
            </div>
          </el-col>

          <el-col :span="6">
            <div class="info-item">
              <span class="label">居民标签</span>
              <div class="tags">
                <el-tag
                  v-for="(tag, index) in residentData.tag"
                  :key="index"
                  :type="getTagType(index)"
                  size="small"
                >
                  {{ tag }}
                </el-tag>
                <span v-if="!residentData.tag || residentData.tag.length === 0" class="value">无</span>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <span class="label">性别</span>
              <span class="value">{{ getGenderText(residentData.gender) }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <span class="label">出生日期</span>
              <span class="value">{{ formatDateTime(residentData.birthdate) || '' }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <span class="label">籍贯</span>
              <span class="value">{{ residentData.originPlace || '' }}</span>
            </div>
          </el-col>

          <el-col :span="6">
            <div class="info-item">
              <span class="label">民族</span>
              <span class="value">{{ residentData.nation || '' }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <span class="label">文化程度</span>
              <span class="value">{{ residentData.education || '' }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <span class="label">婚姻状况</span>
              <span class="value">{{ residentData.maritalStatus || '' }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <span class="label">职业</span>
              <span class="value">{{ residentData.occupation || '' }}</span>
            </div>
          </el-col>

          <el-col :span="6">
            <div class="info-item">
              <span class="label">费用类型</span>
              <span class="value">{{ residentData.costType || '' }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <span class="label">定点医疗单位</span>
              <span class="value">{{ residentData.medicalUnit || '' }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <span class="label">来源</span>
              <span class="value">{{ residentData.source || '' }}</span>
            </div>
          </el-col>
        </el-row>
      </div>

      <!-- 健康信息 -->
      <div class="section">
        <h3 class="section-title">健康信息</h3>
        <el-row :gutter="20" class="info-grid">
          <el-col :span="6">
            <div class="info-item">
              <span class="label">身高</span>
              <span class="value">{{ healthData.height || '' }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <span class="label">体重</span>
              <span class="value">{{ healthData.weight || '' }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <span class="label">血型</span>
              <span class="value">{{ healthData.bloodType || '' }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <span class="label">RH阴性</span>
              <span class="value">{{ getRhNegativeText(healthData.rhNegative) }}</span>
            </div>
          </el-col>

          <el-col :span="6">
            <div class="info-item">
              <span class="label">过敏史</span>
              <span class="value">{{ healthData.allergyHistory || '无' }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <span class="label">既往史</span>
              <span class="value">{{ healthData.medicalHistory || '无' }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <span class="label">就诊史</span>
              <span class="value">{{ healthData.visitHistory || '无' }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="info-item">
              <span class="label">家族病史</span>
              <span class="value">{{ healthData.familyHistory || '无' }}</span>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>

    <!-- 短信发送对话框 -->
    <el-dialog
      v-model="smsDialogVisible"
      title="发送短信"
      width="500px"
      :before-close="handleSmsDialogClose"
    >
      <el-form :model="smsForm" label-width="100px" class="sms-form">
        <el-form-item label="居民姓名">
          <el-input v-model="smsForm.name" disabled />
        </el-form-item>
        <el-form-item label="手机号码">
          <el-input v-model="smsForm.phone" disabled />
        </el-form-item>
        <el-form-item label="身份证号">
          <el-input v-model="smsForm.idCard" disabled />
        </el-form-item>
        <el-form-item label="短信内容" required>
          <el-input
            v-model="smsForm.content"
            type="textarea"
            :rows="4"
            placeholder="暂时不支持自定义短信..."
            maxlength="200"
            disabled
            show-word-limit
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleSmsDialogClose">取消</el-button>
          <el-button
            type="primary"
            @click="sendSms"
            :loading="smsSending"

          >
<!--            :disabled="!smsForm.content.trim()"-->
            发送短信
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { ChatDotRound } from '@element-plus/icons-vue'

// Props
const props = defineProps({
  residentId: {
    type: [String, Number],
    required: true
  }
})

// 响应式数据
const loading = ref(false)
const residentData = reactive({})
const healthData = reactive({})
const tagOptions = ref([])

// 短信相关数据
const smsDialogVisible = ref(false)
const smsSending = ref(false)
const smsForm = reactive({
  name: '',
  phone: '',
  idCard: '',
  content: ''
})

// 方法
const loadResidentDetail = async () => {
  if (!props.residentId) {
    console.warn('居民ID不存在')
    return
  }

  loading.value = true
  try {
    const res = await axios.get(`/resident/getResidentById?id=${props.residentId}`)
    const data = res.data
    console.log('加载居民详情数据:', data)

    Object.assign(residentData, {
      residentNumber: data.id || '',
      name: data.name || '',
      avatar: data.avatar || '',
      idCard: data.idCard || '',
      phone: data.phone || '',
      address: data.address || '',
      password: data.password || '',
      district: data.district || '',
      gender: data.gender !== undefined && data.gender !== null ? data.gender : '',
      birthdate: data.birthdate || '',
      originPlace: data.originPlace || '',
      nation: data.nation || '',
      medicalUnit: data.medicalUnit || '',
      maritalStatus: data.maritalStatus || '',
      occupation: data.occupation || '',
      householdType: data.householdType || '',
      costType: data.costType || '',
      education: data.education || '',
      source: data.source || '',
      tag: data.tag || []
    })

    if (data.health) {
      Object.assign(healthData, {
        height: data.health.height ? `${data.health.height}cm` : '',
        weight: data.health.weight ? `${data.health.weight}kg` : '',
        bloodType: data.health.bloodType || '',
        rhNegative: data.health.rhNegative !== undefined && data.health.rhNegative !== null ? data.health.rhNegative : null,
        allergyHistory: getHistoryText(data.health.allergyHistory),
        medicalHistory: getHistoryText(data.health.medicalHistory),
        visitHistory: getHistoryText(data.health.visitHistory),
        familyHistory: getHistoryText(data.health.familyHistory)
      })
    } else {
      Object.assign(healthData, {
        height: '',
        weight: '',
        bloodType: '',
        rhNegative: null,
        allergyHistory: '无',
        medicalHistory: '无',
        visitHistory: '无',
        familyHistory: '无'
      })
    }

  } catch (error) {
    console.error('加载居民详情失败:', error)
    ElMessage.error('加载居民详情失败')
  } finally {
    loading.value = false
  }
}

const getAllTag = async () => {
  try {
    const resp = await axios.get("/tag/getAllTag")
    tagOptions.value = resp.data || []
  } catch (error) {
    console.error('加载标签失败:', error)
  }
}

const getAvatarUrl = (avatar) => {
  if (!avatar) return '/default-avatar.png'
  if (avatar.startsWith('http')) return avatar
  return `http://localhost:8080/images/${avatar}`
}

const formatDateTime = (dateStr) => {
  if (!dateStr) return '-'

  try {
    const date = new Date(dateStr)
    if (isNaN(date.getTime())) return '-'

    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      hour12: false
    })
  } catch (error) {
    console.error('日期时间格式化错误:', error)
    return '-'
  }
}

const getTagType = (index) => {
  const types = ['danger', 'success', 'warning', 'info']
  return types[index % types.length]
}

const getRhNegativeText = (value) => {
  if (value === null || value === undefined) return ''
  return value === 1 || value === true ? '是' : '否'
}

const getHistoryText = (value) => {
  if (!value || value === '' || value === null || value === undefined) {
    return '无'
  }
  if (value === '无') {
    return '无'
  }
  return value
}

const getGenderText = (value) => {
  if (value === null || value === undefined) return '未知'
  if (value === 0 || value === '0') return '女'
  if (value === 1 || value === '1') return '男'
  return value
}

// 短信相关方法
const openSmsDialog = () => {
  if (!residentData.phone) {
    ElMessage.warning('该居民没有手机号码')
    return
  }

  // 填充表单数据
  smsForm.name = residentData.name || ''
  smsForm.phone = residentData.phone || ''
  smsForm.idCard = residentData.idCard || ''
  smsForm.content = ''

  smsDialogVisible.value = true
}

const handleSmsDialogClose = () => {
  smsDialogVisible.value = false
  smsForm.content = ''
}

const sendSms = async () => {
  // if (!smsForm.content.trim()) {
  //   ElMessage.warning('请输入短信内容')
  //   return
  // }

  smsSending.value = true
  try {
    const params = {
      residentId: props.residentId,
      name: smsForm.name,
      phone: smsForm.phone,
      idCard: smsForm.idCard,
      content: smsForm.content.trim()
    }

    axios.post(`/resident/getTelCode/${smsForm.phone}`).then(resp => {
      console.log(smsForm.phone)
      console.log(smsForm.content)
      ElMessage.success("发送成功")
    })

    // 模拟发送成功
    await new Promise(resolve => setTimeout(resolve, 1500))

    ElMessage.success('短信发送成功！')
    handleSmsDialogClose()

  } catch (error) {
    console.error('短信发送失败:', error)
    ElMessage.error('短信发送失败，请重试')
  } finally {
    smsSending.value = false
  }
}

watch(() => props.residentId, (newVal) => {
  if (newVal) {
    loadResidentDetail()
  }
})

onMounted(() => {
  loadResidentDetail()
  getAllTag()
})
</script>

<style scoped>
.health-profile {
  background: transparent;
}

.loading {
  text-align: center;
  padding: 50px;
}

.section {
  margin-bottom: 40px;
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin: 0 0 25px 0;
}

.info-grid {
  margin: 0;
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  min-height: 36px;
}

.label {
  display: inline-block;
  width: 100px;
  font-size: 14px;
  color: #606266;
  margin-right: 8px;
  flex-shrink: 0;
}

.value {
  font-size: 14px;
  color: #303133;
  word-break: break-all;
}

.avatar-wrapper {
  display: flex;
  align-items: center;
}

.avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  object-fit: cover;
  background: #f0f0f0;
}

.phone-wrapper {
  display: flex;
  align-items: center;
  gap: 10px;
}

.sms-btn {
  font-size: 12px;
  padding: 4px 8px;
  height: 24px;
  border-radius: 4px;
}

.sms-form {
  padding: 20px 0;
}

.sms-form .el-form-item {
  margin-bottom: 20px;
}

.sms-form .el-input.is-disabled .el-input__inner {
  background-color: #f5f7fa;
  color: #909399;
}

.dialog-footer {
  text-align: right;
}

.dialog-footer .el-button {
  margin-left: 10px;
}

.tags {
  display: flex;
  gap: 5px;
  flex-wrap: wrap;
  align-items: center;
}

.tags .el-tag {
  margin: 0;
}
</style>